package com.shop.socket.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author Song Yinghui
 * @date 2019/12/13
 * @Version 1.0
 */
public class SocketClient {

    public void start() throws IOException {
        String host = "127.0.0.1";
        int port = 5555;
        Socket socket = new Socket(host,port);
        OutputStream outputStream = socket.getOutputStream();
        String sendMsg = "Hello , I'm client ,this is a test message, please call back when you received ! ";
        outputStream.write(sendMsg.getBytes(StandardCharsets.UTF_8));
        // todo 此处不能调用 outputStream.close(); 这样的话 会直接关闭outputStream 相应的socket也会直接关闭，
        // todo 会导致下方调用socket.getInputStream()时出错，因为此时的socket 已经在outputStream.close()时关闭
        socket.shutdownOutput(); //通知服务端，客户端消息已经发送完毕，等待服务端回复，并未关闭socket
        //等到server 端回复消息
        InputStream inputStream = socket.getInputStream();
        StringBuilder stringBuilder = new StringBuilder();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            stringBuilder.append(new String(buffer, 0, len, Charset.forName("utf-8")));
        }
        System.out.println("This is server replay :"+stringBuilder.toString());
        inputStream.close();
        socket.close();
    }

    public static void main(String[] args) throws IOException {
        new SocketClient().start();
    }
}
